package net.mayee.common;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;

/**
 * Created by mayee on 15/9/15.
 */
public class SearchFilter {
    public enum Operator {
        EQ, LIKE, GT, LT, GTE, LTE
    }

    public String fieldName;
    public Object value;
    public Operator operator;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.value = value;
        this.operator = operator;
    }

    public static Map<String, SearchFilter> parse(
            Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = Maps.newHashMap();

        for (Entry<String, Object> entry : searchParams.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (StringUtils.isBlank((String) value)) {
                continue;
            }

            String[] names = StringUtils.split(key, "_");
            StringBuilder name = new StringBuilder(names[1]);
            if (names.length < 2) {
                continue;
            }
            for (int i = 2, n = names.length; i < n; i++) {
                name.append("_").append(names[i]);
            }

            SearchFilter filter = new SearchFilter(name.toString(),
                    Operator.valueOf(names[0]), value);
            filters.put(key, filter);
        }

        return filters;
    }
}
